<template>
  <div class="merchant-form-modal" v-if="visible">
    <div class="modal-backdrop" @click="closeModal"></div>
    <div class="modal-container">
      <div class="modal-header">
        <h2 class="modal-title">{{ isEdit ? '编辑商户' : '添加商户' }}</h2>
        <button class="close-btn" @click="closeModal">
          <i class="fas fa-times"></i>
        </button>
      </div>

      <div class="modal-body">
        <form @submit.prevent="submitForm" class="merchant-form">
          <!-- 商户名称 -->
          <div class="form-group">
            <label for="merchant-name" class="required">商户名称</label>
            <input type="text" id="merchant-name" v-model="formData.user_name" :class="{ error: errors.name }"
              placeholder="请输入商户名称" />
            <span class="error-message" v-if="errors.name">{{ errors.name }}</span>
          </div>

          <div class="form-group">
            <label for="merchant-name" class="required">封面图</label>
            <Upload v-model="formData.shop_cover_list" />
          </div>

          <div class="form-group">
            <label for="merchant-name" class="required">Banner图</label>
            <Upload v-model="formData.shop_banner_list" max-count="99" />
          </div>

          <!-- 商户类别 -->
          <div class="form-group">
            <label for="merchant-category">商户类别</label>
            <MerchantTypeSelect v-model="formData.shop_class" :multiple="true" />
          </div>

          <div class="form-group">
            <label for="merchant-description">商户星级</label>
            <input id="merchant-description" v-model="formData.star" placeholder="请输入商户星级" rows="2"></input>
          </div>
          <div class="form-group">
            <label for="merchant-description">店铺假销量</label>
            <input id="merchant-description" v-model="formData.buy_num" placeholder="请输入店铺假销量" rows="2"></input>
          </div>
          <div class="form-group">
            <label for="merchant-description">店铺描述</label>
            <textarea id="merchant-description" v-model="formData.shop_describe" placeholder="请输入店铺描述"
              rows="4"></textarea>
          </div>

          <el-form-item label="是否热门" prop="is_hot">
            <el-radio-group v-model="formData.characteristic" class="ml-4">
              <el-radio :label="0" :value="0" size="large">否</el-radio>
              <el-radio :label="1" :value="1" size="large">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 商户状态 -->
          <div class="form-group">
            <label for="merchant-category">商户状态</label>

            <el-select v-model="formData.status" placeholder="请选择商户状态" size="large">
              <el-option v-for="item in shopStatus" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>

          <!-- 商户地址 -->
          <div class="form-group">
            <label for="merchant-address">商户地址</label>
            <input type="text" id="merchant-address" v-model="formData.shop_address" placeholder="请输入商户地址" />
          </div>
        </form>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn-cancel" @click="closeModal">取消</button>
        <button type="button" class="btn-submit" @click="submitForm">保存</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineProps, defineEmits } from 'vue'
import Select from '@/components/admin/Select.vue'
import MerchantTypeSelect from '@/components/admin/merchants/MerchantTypeSelect.vue'
import Upload from '@/components/Upload.vue'

// 定义Props和Emits
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  merchantData: {
    type: Object as () => {
      id: string
      name: string
      logo: string
      description: string
      category: string
      status: string
      contactPerson: string
      contactPhone: string
      email: string
      address: string
      [key: string]: any
    },
    default: () => ({}),
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  shopStatus: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['update:visible', 'submit', 'closeModal'])

// 表单数据
const formData = ref({
  user_name: '',
  user_cover: '',
  shop_cover_list: '',
  shop_banner_list: '',
  remarks: '',
  shop_class: '',
  status: '',
  address: '',
  buy_num: '',
  shop_describe: '',
  star: '',
  shop_address: '',
  characteristic: ''
  // 其他字段会保留原始值
})

watch(() => props.merchantData, (newVal) => {
  console.log(777, formData.value);

  Object.assign(formData.value, newVal)
}, {
  immediate: true,
  deep: true
})


// 表单错误信息
const errors = ref({
  name: '',
})

// 文件上传相关
const fileInput = ref<HTMLInputElement | null>(null)
const previewImage = ref('')

// 重置表单
function resetForm() {
  formData.value = {
    id: '',
    user_name: '',
    user_cover: '',
    remarks: '',
    shop_class: '',
    status: '',
    address: '',
    buy_num: '',
    shop_describe: '',
    star: '',
    shop_address: '',
    characteristic: ''
  }
  errors.value = { name: '' }
  previewImage.value = ''
}

// 触发文件选择
function triggerFileInput() {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

// 处理文件选择
function handleFileChange(event: Event) {
  const target = event.target as HTMLInputElement
  if (target.files && target.files.length > 0) {
    const file = target.files[0]
    const reader = new FileReader()
    reader.onload = (e) => {
      if (e.target?.result) {
        previewImage.value = e.target.result as string
        // 在实际项目中，这里应该调用上传API
        // formData.value.logo = 上传成功后的URL
      }
    }
    reader.readAsDataURL(file)
  }
}

// 移除Logo
function removeLogo() {
  formData.value.logo = ''
  previewImage.value = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 验证表单
function validateForm() {
  let isValid = true

  // 重置错误信息
  // errors.value = { name: '' };

  // // 验证商户名称
  // if (!formData.value.name.trim()) {
  //   errors.value.name = '商户名称不能为空';
  //   isValid = false;
  // }

  return isValid
}

// 提交表单
function submitForm() {
  if (validateForm() || true) {
    // 在实际项目中，这里会调用API保存数据
    // 如果是编辑模式，需要区分处理

    const submitData = {
      ...formData.value,
      // 如果有预览图但没有保存的logo URL，使用预览图
      logo: formData.value.logo || previewImage.value,
    }

    emit('submit', submitData)

    //closeModal()
  }
}

// 关闭模态框
function closeModal() {
  resetForm()

  emit('update:visible', false)

  emit('closeModal')
}

// -----------------------------
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';
@import '@/assets/styles/mixins.scss';

.merchant-form-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: $z-index-modal;
}

.modal-backdrop {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba($black, 0.5);
  z-index: $z-index-modal-backdrop;
}

.modal-container {
  position: relative;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  background-color: $white;
  border-radius: $border-radius-lg;
  box-shadow: $shadow-xl;
  z-index: $z-index-modal;
  display: flex;
  flex-direction: column;
  animation: modalFadeIn 0.3s ease-out;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-md $spacing-lg;
  border-bottom: 1px solid $gray-200;

  .modal-title {
    margin: 0;
    font-size: $font-size-xl;
    font-weight: $font-weight-bold;
    color: $text-primary;
  }

  .close-btn {
    background: transparent;
    border: none;
    font-size: $font-size-lg;
    color: $gray-500;
    cursor: pointer;
    padding: $spacing-xs;
    border-radius: $border-radius-full;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all $transition-base;

    &:hover {
      background-color: $gray-100;
      color: $gray-700;
    }
  }
}

.modal-body {
  padding: $spacing-lg;
  overflow-y: auto;
  flex: 1;
}

.modal-footer {
  padding: $spacing-md $spacing-lg;
  display: flex;
  justify-content: flex-end;
  gap: $spacing-md;
  border-top: 1px solid $gray-200;
}

.merchant-form {
  display: flex;
  flex-direction: column;
  gap: $spacing-md;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: $spacing-xs;

  label {
    font-size: $font-size-sm;
    font-weight: $font-weight-medium;
    color: $text-secondary;

    &.required::after {
      content: '*';
      color: $danger;
      margin-left: 4px;
    }
  }

  input,
  select,
  textarea {
    padding: $spacing-sm;
    border: 1px solid $gray-300;
    border-radius: $border-radius-md;
    font-size: $font-size-md;
    color: $text-primary;
    outline: none;
    transition: border-color $transition-base;

    &:focus {
      border-color: $primary;
      box-shadow: 0 0 0 2px rgba($primary, 0.1);
    }

    &.error {
      border-color: $danger;
    }
  }

  textarea {
    resize: vertical;
    min-height: 100px;
  }

  .error-message {
    font-size: $font-size-xs;
    color: $danger;
  }
}

.form-section {
  margin-top: $spacing-lg;
  padding-top: $spacing-md;
  border-top: 1px solid $gray-200;

  .section-title {
    margin: 0 0 $spacing-md;
    font-size: $font-size-lg;
    font-weight: $font-weight-semibold;
    color: $text-primary;
  }
}

.logo-upload {
  .preview-area {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: $border-radius-md;
    overflow: hidden;
    border: 1px solid $gray-300;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .remove-btn {
      position: absolute;
      bottom: $spacing-xs;
      right: $spacing-xs;
      width: 28px;
      height: 28px;
      border-radius: $border-radius-full;
      background-color: rgba($black, 0.7);
      color: $white;
      border: none;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: background-color $transition-base;

      &:hover {
        background-color: rgba($danger, 0.8);
      }
    }
  }

  .upload-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2px dashed $gray-300;
    border-radius: $border-radius-md;
    padding: $spacing-lg;
    cursor: pointer;
    transition: all $transition-base;

    i {
      font-size: $font-size-2xl;
      color: $gray-400;
      margin-bottom: $spacing-sm;
    }

    span {
      color: $text-secondary;
      font-size: $font-size-sm;
    }

    .upload-hint {
      color: $text-tertiary;
      font-size: $font-size-xs;
      margin-top: $spacing-xs;
    }

    &:hover {
      border-color: $primary;
      background-color: rgba($primary, 0.05);

      i,
      span {
        color: $primary;
      }
    }
  }
}

.btn-cancel {
  padding: $spacing-xs $spacing-lg;
  border: 1px solid $gray-300;
  border-radius: $border-radius-md;
  background-color: $white;
  color: $text-secondary;
  font-size: $font-size-sm;
  font-weight: $font-weight-medium;
  cursor: pointer;
  transition: all $transition-base;

  &:hover {
    background-color: $gray-100;
    border-color: $gray-400;
  }
}

.btn-submit {
  padding: $spacing-xs $spacing-lg;
  border: none;
  border-radius: $border-radius-md;
  background-color: $primary;
  color: $white;
  font-size: $font-size-sm;
  font-weight: $font-weight-medium;
  cursor: pointer;
  transition: all $transition-base;

  &:hover {
    background-color: darken($primary, 5%);
  }
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式调整
@media (max-width: $breakpoint-md) {
  .modal-container {
    width: 95%;
    max-height: 95vh;
  }

  .form-section {
    margin-top: $spacing-md;
    padding-top: $spacing-sm;
  }
}
</style>
